import json
from datetime import datetime

from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from django.views import View
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from bilibili_management import settings
from user.models import SysUser
from user.serializers import SysUserUpdateSerializer
import os

@method_decorator(csrf_exempt, name='dispatch')
class ImageView(APIView):
    permission_classes = [AllowAny]
    def post(self, request):
        print("✅ ImageView APIView 触发了")
        file = request.FILES.get('avatar')
        print("file:", file)
        if file:
            file_name = file.name
            suffixName = file_name[file_name.rfind("."):]  # 截取文件后缀
            new_file_name = datetime.now().strftime('%Y%m%d%H%M%S') + suffixName
            upload_dir = os.path.join(settings.MEDIA_ROOT, "userAvatar")
            os.makedirs(upload_dir, exist_ok=True)
            file_path = os.path.join(upload_dir, new_file_name)
            print("file_path:", file_path)
            try:
                with open(file_path, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
                return Response({'code': 200, 'title': new_file_name})
            except Exception as e:
                return Response({'code': 500, 'errorInfo': '上传头像失败'})
        else:
            return Response({'code': 400, 'errorInfo': '未检测到文件'})

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 暂时跳过 CSRF 校验
class AvatarView(APIView):

    def post(self, request):
        print("✅ AvatarView 触发")
        data = request.data  # DRF 提供的数据方式，无需手动 decode
        user_id = data.get('id')
        avatar = data.get('avatar')

        if not user_id or not avatar:
            return Response({'code': 400, 'msg': '缺少参数'})

        try:
            user = SysUser.objects.get(id=user_id)
            user.avatar = avatar
            user.save()
            return Response({'code': 200, 'msg': '头像更新成功'})
        except SysUser.DoesNotExist:
            return Response({'code': 404, 'msg': '用户不存在'})

class UserUpdateView(APIView):
    permission_classes = [AllowAny]
    def post(self, request):
        data = request.data
        print("📥 收到数据:", data)

        user_id = data.get("id")  # ✅ 根据 id 查询

        # ✅ 新增用户逻辑开始
        if user_id == -1:
            if SysUser.objects.filter(username=data['username']).exists():
                return Response({"code": 400, "msg": "用户名已存在"})

            user = SysUser(
                username=data['username'],
                password=make_password("123456"),
                email=data.get("email", ""),
                phonenumber=data.get("phonenumber", ""),
                status=data.get("status", 1),
                remark=data.get("remark", ""),
                avatar="default.jpg",
                create_time=datetime.now().date()
            )
            user.save()
            return Response({"code": 200, "msg": "添加成功！"})
        # ✅ 新增用户逻辑结束

        # ✅ 这行是关键修正
        if user_id is None:
            return Response({"code": 400, "msg": "缺少用户 ID"})

        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return Response({"code": 404, "msg": "用户不存在"})

        serializer = SysUserUpdateSerializer(user, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"code": 200, "msg": "修改成功！"})
        return Response({"code": 400, "msg": "参数错误", "errors": serializer.errors})